/** * 基础信息-客商管理 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">基础信息</el-breadcrumb-item>
      <el-breadcrumb-item>客商管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search" align="left">
      <el-form-item>
        <el-upload class="upload-demo" action="/api/merchants/import" 
        :headers="headers" :on-success="handlesuccess" :before-upload="beforeUpload">
          <el-button size="small" type="success">导入</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="exportData()">导出</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">新增</el-button>
        <el-button size="small" type="danger" @click="batchDel()">批量删除</el-button>
      </el-form-item>
      <el-form-item label="搜索:">
        <el-input size="small" v-model="formInline.name" placeholder="客商名称" class="searchInput"/>
        <el-select size="small" v-model="formInline.merchants_attribute" placeholder="选择属性" class="searchSelect">
            <el-option v-for="item in selectOption.attributeOption" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-select size="small" v-model="formInline.merchants_industry" placeholder="选择行业" class="searchSelect">
            <el-option v-for="item in selectOption.industryOption" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-select size="small" v-model="formInline.isEnable" placeholder="是否启用" class="searchSelect">
            <el-option label="启用" value="1"/>
            <el-option label="未启用" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="getdata()">搜索</el-button>
        <el-button size="small" type="danger" @click="clearConditon()">重置</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row @sort-change="sortChange" ref="multipleSelectable"
      border  @selection-change="handleSelectionChange" style="width: 100%" :row-key="getRowKeys" >
      <el-table-column align="center" type="selection" width="40" :reserve-selection="true"/>
      <el-table-column align="center" prop="id" label="序号" width="50"/>
      <el-table-column align="center" prop="code" label="客商编码" width="70"/>
      <el-table-column align="center" prop="name" label="客商名称" width="100"/>
      <el-table-column align="center" prop="merchants_type" label="客商分类" width="70"/>
      <el-table-column align="center" prop="short_name" label="客商简称" width="70"/>
      <el-table-column align="center" prop="merchants_grade" label="客商等级" width="70"/>
      <el-table-column align="center" prop="merchants_attribute" label="客商属性" width="70"/>
      <el-table-column align="center" prop="merchants_industry" label="客商行业" width="70"/>
      <el-table-column align="center" prop="contacts" label="联系人" width="70"/>
      <el-table-column align="center" prop="telephone" label="电话" width="100"/>
      <el-table-column align="center" prop="fax" label="传真" width="100"/>
      <el-table-column align="center" prop="email" label="邮箱" width="150"/>
      <el-table-column align="center" prop="address" label="地址" width="150"/>
      <el-table-column align="center" prop="country" label="国家" width="70"/>
      <el-table-column align="center" prop="isEnable" label="启用" width="70">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isEnable=='1'?nshow:fshow" @change="editEnable(scope.row)" active-color="#13ce66" inactive-color="#ff4949"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteOne(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination :child-msg="pageparm" @callFather="callFather" align="center"/>
    <!-- 新增、编辑页面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="55%" :before-close="closeDialog">
      <el-form :inline="true" label-width="100px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="客商编码" prop="code">
          <el-input size="small" v-model="editForm.code" placeholder="示例：KS01"/>
        </el-form-item>
        <el-form-item label="客商名称" prop="name">
          <el-input size="small" v-model="editForm.name" placeholder="示例：蜗牛学院"/>
        </el-form-item>
        <el-form-item label="客商分类" prop="merchants_type">
          <el-select size="small" v-model="editForm.merchants_type" placeholder="请选择" class="mySelect">
            <el-option v-for="item in selectOption.typeOption" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="客商简称" prop="short_name">
          <el-input size="small" v-model="editForm.short_name" placeholder="示例：蜗牛"/>
        </el-form-item>
        <el-form-item label="客商等级" prop="merchants_grade">
          <el-select size="small" v-model="editForm.merchants_grade" placeholder="请选择" class="mySelect">
            <el-option v-for="item in selectOption.gradeOption" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="客商属性" prop="merchants_attribute">
          <el-select size="small" v-model="editForm.merchants_attribute" placeholder="请选择" class="mySelect">
            <el-option v-for="item in selectOption.attributeOption" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="客商行业" prop="merchants_industry">
          <el-select size="small" v-model="editForm.merchants_industry" placeholder="请选择" class="mySelect">
            <el-option v-for="item in selectOption.industryOption" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input size="small" v-model="editForm.contacts"/>
        </el-form-item>
        <el-form-item label="电话" prop="telephone">
          <el-input size="small" v-model="editForm.telephone"/>
        </el-form-item>
        <el-form-item label="传真" prop="fax">
          <el-input size="small" v-model="editForm.fax"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input size="small" v-model="editForm.email"/>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input size="small" v-model="editForm.address"/>
        </el-form-item>
        <el-form-item label="国家" prop="country">
          <el-input size="small" v-model="editForm.country"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button size="small" @click="cancelDialog">取消</el-button>
        <el-button size="small" type="primary" class="title"
          @click="submitForm()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination";
export default {
  
  data() {
    //校验器
    var checkCode = (rule, value, callback) => {
      //判断是否为修改
      if(!this.editFormType && this.editObj.code===value){
        callback();
      }
      this.$axios.get("/api/merchants/code/"+value).then(Response => {
          if(Response.data.code==500) {
            callback();
          } 
          callback(new Error('编码已存在！'));
      })
    };
    var checkName = (rule, value, callback) => {
      //判断是否为修改
      if(!this.editFormType && this.editObj.name===value){
        callback();
      }
      this.$axios.get("/api/merchants/name/"+encodeURI(encodeURI(value))).then(Response => {
          if(Response.data.code==500) {
            callback();
          } 
          callback(new Error('名称已存在！'));
      })
    };
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      // 控制编辑页面显示与隐藏
      editFormVisible: false, 
      // 编辑页面是否新增
      editFormType: true, 
      // 进行修改的对象
      editObj:{},
      // 新增、编辑页面的标题
      title: "添加",
      // 编辑页面数据
      editForm: {
        id: "",
        code: "",
        name: "",
        merchants_type: "",
        short_name: "",
        merchants_grade: "",
        merchants_attribute: "",
        merchants_industry: "",
        contacts: "",
        telephone: "",
        fax: "",
        email: "",
        address: "",
        country: "",
      },
      // 验证规则
      rules: {
        code: [
          {required: true,message: '请输入客商编码', trigger: 'blur'},
          {pattern:/^[A-Za-z0-9]{4}$/, message: '请输入4位数字、字母', trigger: 'blur'},
          {validator: checkCode, trigger: 'blur' }
        ],
        name: [
          {required: true, message: '请输入客商名称', trigger: 'blur' },
          {min: 1, max: 20, message: '请输入1~20个字符', trigger: 'blur' },
          {validator: checkName, trigger: '' }
        ],
        merchants_type: [
          {required: true, message: '请选择客商类型', trigger: 'blur' }
        ],
        merchants_grade: [
          {required: true, message: '请选择客商等级', trigger: 'blur' }
        ],
        merchants_attribute: [
          {required: true, message: '请选择客商属性', trigger: 'blur' }
        ],
        merchants_industry: [
          {required: true, message: '请选择客商行业', trigger: 'blur' }
        ],
        contacts: [
          {required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        telephone: [
          {required: true, message: '请输入电话', trigger: 'blur' },
          {pattern: /^1[3456789]\d{9}$/, message: '电话格式错误', trigger: 'blur' }
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur' },
          {type: 'email', message: '邮箱格式错误', trigger: 'blur' }
        ],
        address: [
          {required: true, message: '请输入地址', trigger: 'blur' },
          {min: 1, max: 50, message: '请输入1~50个字符', trigger: 'blur' }
        ],
      },
      // 搜索框数据
      formInline: {
        name: "",
        merchants_attribute: "",
        merchants_industry: "",
        isEnable:"",
      },
      // 表单数据
      listData: [], 
      // 表单选择数组
      multipleSelection: [],
      // 初始化分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
      },
      //下拉框
      selectOption:{
        // 客商分类下拉框
        typeOption:[],
        // 客商等级下拉框
        gradeOption:[],
        // 客商属性下拉框
        attributeOption:[],
        // 客商行业下拉框
        industryOption:[]
      },
      // 排序字段
      orderSort:"",
      orderKey:"",
      // 文件上传的headers

    };
  },
  // 注册组件
  components: {Pagination},

  //创建完毕
  created() {
    //渲染表单
    this.getdata();
    //渲染下拉框
    this.getSelectData();
  },
  // 获取token
  computed: {
    headers() {
      return{
        "Authorization": localStorage.getItem('logintoken')
      }
    }
  },
  // 定义方法
  methods: {
    // 清空搜索条件
    clearConditon(){
      this.formInline.name= "";
      this.formInline.merchants_attribute= "";
      this.formInline.merchants_industry= "";
      this.formInline.isEnable="";
      this.getdata();
    },
    // 获取表单数据
    getdata() {
      let queryEntity={
        currentPage:this.pageparm.currentPage,
        pageSize:this.pageparm.pageSize,
        entity:this.formInline,
        orderSort:this.orderSort,
        orderKey:this.orderKey
      };
      this.$axios.post("/api/merchants/condition",queryEntity)
      .then((res) => {
          if (res.data.code == 200) {
              this.listData = res.data.data.list;
              //对总数量进行赋值
              this.pageparm.total = res.data.data.total;
          }else{
              this.$message({type: 'info',message: res.data.message})
          }
      })
      .catch(err => {
          this.$message.error('数据加载失败，请稍后再试！')
      })
    },
    // 分页插件事件
    callFather(parm) {
      this.pageparm.currentPage = parm.currentPage;
      this.pageparm.pageSize = parm.pageSize;
      this.getdata();
    },
    // 获取下拉框数据
    getSelectData(){
      this.$axios.get("/api/merchants/select")
        .then((res) => {
            if (res.data.code == 200) {
                this.selectOption = res.data.data;
            }else{
                this.$message({type: 'info',message: res.data.message})
            }
        })
        .catch(err => {
            this.$message.error('数据加载失败，请稍后再试！')
        })
    },
    // 排序方法
    sortChange(column) {
        if (column.order == "ascending") {
          this.orderSort = 'asc'
        } else if (column.order == "descending") {
          this.orderSort = 'desc'
        } else {
          this.orderSort = ''
        }
        this.orderKey=column.prop;
        this.getdata();
      },
    //显示新增、编辑界面
    handleEdit: function (obj) {
      this.editFormVisible = true;
      if (obj != undefined && obj != "undefined") {
        this.editObj=obj;
        this.editFormType=false;
        this.title = "修改";
        //填充数据
        this.editForm.id = obj.id;
        this.editForm.code = obj.code;
        this.editForm.name = obj.name;
        this.editForm.merchants_type = obj.merchants_type;
        this.editForm.short_name = obj.short_name;
        this.editForm.merchants_grade = obj.merchants_grade;
        this.editForm.merchants_attribute = obj.merchants_attribute;
        this.editForm.merchants_industry = obj.merchants_industry;
        this.editForm.contacts = obj.contacts;
        this.editForm.telephone = obj.telephone;
        this.editForm.fax = obj.fax;
        this.editForm.email = obj.email;
        this.editForm.address = obj.address;
        this.editForm.country = obj.country;
        this.editForm.isEnable = obj.isEnable;
      } else {
        this.editFormType=true;
        this.title = "添加";
        //清空数据
        this.editForm.id = "";
        this.editForm.code = "";
        this.editForm.name = "";
        this.editForm.merchants_type = "";
        this.editForm.short_name = "";
        this.editForm.merchants_grade = "";
        this.editForm.merchants_attribute = "";
        this.editForm.merchants_industry = "";
        this.editForm.contacts = "";
        this.editForm.telephone = "";
        this.editForm.fax = "";
        this.editForm.email = "";
        this.editForm.address = "";
        this.editForm.country = "中国";
        this.editForm.isEnable = "";
      }
    },
    // 编辑、增加页面保存方法
    submitForm() {
      // 参数验证
      this.$refs["editForm"].validate((valid) => {
        if (!valid) {
          this.$message.error("请按要求填写表单！");
        }else{
          // 判断是修改还是新增
          if (this.editForm.id == "") {
            // 新增
            this.$axios.post("/api/merchants/merchants", this.editForm)
            .then((res) => {
                //关闭弹窗
                this.$refs["editForm"].resetFields();
                this.editFormVisible = false;
                if (res.data.code == 200) {
                    //刷新数据
                    this.getdata();
                    this.$message({
                        type: "success",
                        message: "保存成功！",
                    });
                } else {
                    this.$message({
                        type: "info",
                        message: res.data.message,
                    });
                }
            })
            .catch((err) => {
              this.editFormVisible = false;
              this.$message.error(err.response.data.message);
            });
          } else {
            // 修改
            this.$axios.put("/api/merchants/merchants", this.editForm)
            .then((res) => {
              console.log(this.editForm);
                //关闭弹窗
                this.$refs["editForm"].resetFields();
                this.editFormVisible = false;
                if (res.data.code == 200) {
                    //刷新数据
                    this.getdata();
                    this.$message({
                        type: "success",
                        message: "保存成功！",
                    });
                } else {
                    this.$message({
                        type: "info",
                        message: res.data.message,
                    });
                }
            })
            .catch((err) => {
              this.editFormVisible = false;
              this.$message.error(err.response.data.message);
            });
          };
        }
      });
    },
    // 删除一个
    deleteOne(obj) {
      this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
            this.$axios.delete("/api/merchants/merchants/"+obj.id)
            .then((res) => {
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "已删除!",
                });
                this.getdata();
              } else {
                this.$message({
                  type: "info",
                  message: res.data.message,
                });
              }
            })
            .catch((err) => {
              this.$message.error("删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 批量删除
    batchDel() {
        if(this.multipleSelection.length==0){
            this.$message({
                type: "info",
                message: "请先勾选需要删除的列",
            });
            return;
        }
        this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        })
        .then(() => {
            this.$axios.put("/api/merchants/merchants/batchDel",this.multipleSelection)
            .then((res) => {
              this.$refs.multipleSelectable.clearSelection();
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "已删除!",
                });
                this.getdata();
              } else {
                this.$message({
                  type: "info",
                  message: res.data.message,
                });
              }
            })
            .catch((err) => {
              this.$refs.multipleSelectable.clearSelection();
              this.$message.error(err.response.data.message);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 启用开关
    editEnable(obj) {
      let newObj=obj;
      newObj.isEnable=3-obj.isEnable;
      // 修改
      this.$axios.put("/api/merchants/merchants", newObj)
      .then((res) => {
          if (res.data.code == 200) {
              //刷新数据
              this.getdata();
              this.$message({
                  type: "success",
                  message: "操作成功！",
              });
          } else {
              this.$message({
                  type: "info",
                  message: res.data.message,
              });
          }
      })
      .catch((err) => {
        this.editFormVisible = false;
        this.$message.error("操作失败，请稍后再试！");
      });
    },
    // 关闭编辑、增加弹出框
    cancelDialog() {
      this.$refs["editForm"].resetFields();
      this.editFormVisible = false;
    },
    // 关闭前清空验证信息
    closeDialog(done){
      this.$refs["editForm"].resetFields();
      done();
    },
    // 处理表单多选
    handleSelectionChange(val) {
        this.multipleSelection=[];
        for(let index in val){
            this.multipleSelection[index]=val[index].id;
        }
    },
    getRowKeys(row) {
      return row.id;
    },
    // 上传前判断文件格式
    beforeUpload(file) {
      console.log(file.type);
       const type = file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      if (!type) {
        this.$message.error("请上传EXCEL格式的文件!");
      }
      return type;
    },
    //上传成功回调方法
    handlesuccess(res) {
      if (res.code == 200) {
        //刷新数据
        this.getdata();
        this.$message({
            type: "success",
            message: "操作成功！",
        });
      } else {
        this.$message({
            type: "info",
            message: res.message,
        });
      }
    },
    exportData(){
      this.$axios.get("/api/merchants/export",{
        responseType: 'blob'
      }).then(response=> {
        //通过header中获取返回的文件名称
        let fileName = response.headers['content-disposition'].split(";")[1].split("filename=")[1]
        let blob = new Blob([response.data], { type: "application/vnd.ms-excel" })
        let downloadElement = document.createElement("a")
        var href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        //指定下载的文件的名称，切记进行decode
        downloadElement.download = decodeURI(fileName)
        document.body.appendChild(downloadElement)
        downloadElement.click()
        //移除临时创建对象，释放资源
        document.body.removeChild(downloadElement)
        window.URL.revokeObjectURL(href)
      });
    }
  },
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.mySelect{
  width: 193px;
}
.searchSelect{
  width: 100px;
}
.searchInput{
  width: 100px;
}
</style>
